package stripes;

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;


/**
 *
 * @author liupenghe
 * 自定义TextStripe类型，其实是继承自Hadoop提供的MapWritable
 *
 */

public class TextStripe extends MapWritable {
    public TextStripe() {
        super();
    }

    /**
     * 重写格式化输出函数，否则以TextOutputFormat输出，文件只会显示该对象的信息
     * 如：TextStripe@75123
     */
    @Override
    public String toString() {
        String res = "";
        for (Entry<Writable, Writable> entry : this.entrySet()) {
            Text key = (Text) entry.getKey();
            DoubleWritable value = (DoubleWritable) entry.getValue();
            res += key.toString() + ":" + value.get() + ";";
        }
        return res;
    }

    /**
     * 添加另一个putAll方法，实现两个TextStripe的相加
     * 自带的不知为何不能叠加，没办法，只能自己动手实现了
     *
     * @param ts
     */
    public void putAll(TextStripe ts) {
        for (Entry<Writable, Writable> entry : ts.entrySet()) {
            Text tsKey = (Text) entry.getKey();
            DoubleWritable tsValue = (DoubleWritable) entry.getValue();
            //如果已包含该健，累加值
            if (this.containsKey(tsKey)) {
                double newValue = ((DoubleWritable) this.get(tsKey)).get() + tsValue.get();
                this.put(tsKey, new DoubleWritable(newValue));
            } else { //如果不包含该健，则加上
                this.put(tsKey, tsValue);
            }
        }
    }

}